package com.zhida.jiyangcenter.modle

import android.os.Bundle
import android.widget.Adapter
import android.widget.ImageView
import androidx.appcompat.widget.AppCompatImageView
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import chooongg.base.annotation.ContentLayout
import chooongg.base.annotation.TitleBar
import chooongg.base.utils.*
import chooongg.base.widget.recyclerView.divider.HorizontalDividerItemDecoration
import chooongg.base.widget.recyclerView.divider.VerticalDividerItemDecoration
import chooongg.http.APIException
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.zhida.jiyangcenter.R
import com.zhida.jiyangcenter.mian.BaseActivity
import com.google.android.material.appbar.AppBarLayout
import com.zhida.jiyangcenter.api.*
import com.zhida.jiyangcenter.buycar.BuyCarActivity
import com.zhida.jiyangcenter.order.ConfirmOrderActivity
import com.zhida.jiyangcenter.utils.glideImage
import com.zhida.jiyangcenter.utils.request
import com.zhida.jiyangcenter.widget.ResizableImageView
import kotlinx.android.synthetic.main.activity_physical_examination.*
import me.zhanghai.android.materialratingbar.MaterialRatingBar
import java.math.RoundingMode


@TitleBar(false)
@ContentLayout(R.layout.activity_physical_examination)
class PhysicalExaminationActivity : BaseActivity() {
    private var statusBarIsLight = true
    val itemAdapter = ShopDetailsActivity.ItemAdapter()
    val imageAdapter = ImageAdapter()
    val adapter = AdapterStore()

    override fun initConfig(savedInstanceState: Bundle?) {
        super.initConfig(savedInstanceState)
        title_bar.navigationIcon(R.drawable.iv_back_fill) {
            finish()
        }
        title_bar.title("详情")
        ctl_physical.minimumHeight = getStatusBarHeight() + resDimenSize(R.dimen.titleBarHeight)
        appbar_layout.addOnOffsetChangedListener(AppBarLayout.OnOffsetChangedListener { appBarLayout, verticalOffset ->
            val minHeight = -appbar_layout.height + ctl_physical.minimumHeight
            val percentage = Math.abs(verticalOffset).toFloat() / Math.abs(minHeight).toFloat()
            when {
                percentage in 0.4f..0.9f -> {
                    title_bar.alpha = ((percentage - 0.4f) / 0.5f)
                    bga_physical.alpha = 1f
                }
                percentage > 0.5f -> {
                    title_bar.alpha = 1f
                    bga_physical.alpha = 0f
                    if (statusBarIsLight) {
                        statusBarIsLight = false
                        setStatusBarLightMode(statusBarIsLight)
                    }
                }
                else -> {
                    title_bar.alpha = 0f
                    bga_physical.alpha = 1f
                    if (!statusBarIsLight) {
                        statusBarIsLight = true
                        setStatusBarLightMode(statusBarIsLight)
                    }
                }
            }
        })

        rv_physical_tab.layoutManager =
            LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        rv_physical_tab.addItemDecoration(
            VerticalDividerItemDecoration.Builder(context).sizeResId(R.dimen.dividerBig)
                .colorResId(R.color.white).build()
        )
        rv_physical_tab.adapter = itemAdapter
        rv_physical_details.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_physical_details.adapter = imageAdapter
        bga_physical.setAdapter { _, itemView, model, _ ->
            if (itemView != null && model != null && model is StoreExaminationInfoEntity.ServeInfo.Path) {
                glideImage(itemView as ImageView, model.path ?: "")
            }
        }
        rv_physical_store.layoutManager = object : LinearLayoutManager(context) {
            override fun canScrollVertically(): Boolean {
                return false
            }
        }
        rv_physical_store.addItemDecoration(
            HorizontalDividerItemDecoration.Builder(context).sizeResId(R.dimen.dividerSmall)
                .colorResId(R.color.colorBack).build()
        )
        rv_physical_store.adapter = adapter
        adapter.setOnItemClickListener { _, view, position ->
            startActivity<HealthyTestStroeActivity> {
                putExtra("uuid", adapter.data[position].uuid)
                putExtra("type", "1")
            }
        }
        button_physical_buy_car.setOnClickListener {
            lifecycleScope.request({
                APIShop.service().shopcarServeAdd(intent.getStringExtra("uuid") ?: "", 1)
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }
            })
        }
        tv_physical_examination_comment_ore.setOnClickListener {
            startActivity<CommentListActivity> {
                putExtra("kind", "4")
                putExtra("uuid", intent.getStringExtra("uuid"))
            }
        }
        tv_physical_buy_car.setOnClickListener {
            startActivity<BuyCarActivity> { }
        }
        button_physical_buy.setOnClickListener {
            startActivity<ConfirmOrderActivity> {
                putExtra("type","ServeDetails")
                putExtra("uuid",intent.getStringExtra("uuid") ?: "")
            }
        }
        iv_physical_comment.setOnClickListener {
            lifecycleScope.request({
                if (!collection)
                    APIAccount.service().collectionAdd("1", intent.getStringExtra("uuid") ?: "")
                else
                    APIAccount.service().collectionDelete("1", intent.getStringExtra("uuid") ?: "")
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    if (!collection)
                        iv_physical_comment.setImageResource(R.drawable.iv_collection_fill)
                    else
                        iv_physical_comment.setImageResource(R.drawable.iv_collection)
                    collection=!collection
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
        }
        tv_physical_comment.setOnClickListener {
            lifecycleScope.request({
                if (!collection)
                    APIAccount.service().collectionAdd("1", intent.getStringExtra("uuid") ?: "")
                else
                    APIAccount.service().collectionDelete("1", intent.getStringExtra("uuid") ?: "")
            }, object : BaseAPI<Any>() {
                override fun onSuccess(t: Any?, state: Int, msg: String) {
                    tipSuccess(msg)
                    if (!collection)
                        iv_physical_comment.setImageResource(R.drawable.iv_collection_fill)
                    else
                        iv_physical_comment.setImageResource(R.drawable.iv_collection)
                    collection=!collection
                }

                override fun onError(e: APIException) {
                    tipFail(e.eMessage)
                }

            })
        }
        getData()
    }

    var collection = false
    private fun getData() {
        lifecycleScope.request({
            APIShop.service().storeExaminationInfo(
                intent.getStringExtra("uuid") ?: "",
                intent.getStringExtra("city") ?: ""
            )
        }, object : BaseAPI<StoreExaminationInfoEntity>() {
            override fun onSuccess(t: StoreExaminationInfoEntity?, state: Int, msg: String) {
                tv_physical_store_money.text = "￥" + t?.serve_info?.price
                tv_physical_now_money.text = "会员价${t?.serve_info?.low_price}元"
                tv_physical_name.text = t?.serve_info?.name
                itemAdapter.setNewData(t?.serve_info?.label?.split("，"))
                imageAdapter.setNewData(t?.serve_info?.description)
                bga_physical.setData(t?.serve_info?.serve_picture, null)
                adapter.setNewData(t?.serve_info?.store)
                collection = t?.serve_info?.collection ?: false
                if (t?.serve_info?.collection == true) {
                    iv_physical_comment.setImageResource(R.drawable.iv_collection_fill)
                } else {
                    iv_physical_comment.setImageResource(R.drawable.iv_collection)
                }
                if (t?.comment.isNullOrEmpty()){
                    cl_comment.gone()
                }else{
                    cl_comment.visible()
                    tv_physical_examination_comment.text="用户评价（${t?.comment_count}）"
                    rv_physical_examination_store.layoutManager=object :LinearLayoutManager(context){
                        override fun canScrollVertically(): Boolean {
                            return false
                        }
                    }
                    rv_physical_examination_store.adapter= CommentAdapter().apply {
                        setNewData(t?.comment)
                    }
                }

            }

            override fun onError(e: APIException) {
                tipFail(e.eMessage)
            }
        })
    }
    class CommentAdapter:BaseQuickAdapter<StoreExaminationInfoEntity.Comment,BaseViewHolder>(R.layout.item_seller_discuss){
        override fun convert(helper: BaseViewHolder, item: StoreExaminationInfoEntity.Comment?) {
            helper.setText(R.id.tv_name, item?.name)
                .setText(R.id.tv_content, item?.content)
                .setText(R.id.tv_time, item?.time)
            glideImage(helper.getView<AppCompatImageView>(R.id.iv_portrait), item?.avatar
                ?: "")
            val product_star = item?.describes!!.toFloat()
            val server_star = item.logistics!!.toFloat()
            val attitude = item.attitude!!.toFloat()
            val overallStar = ((product_star + server_star+attitude) / 3).toBigDecimal().setScale(1, RoundingMode.HALF_UP).toFloat()
            helper.getView<MaterialRatingBar>(R.id.rating_bar).rating = overallStar
            val recyclerView = helper.getView<RecyclerView>(R.id.recycler_picture_view)
            if (recyclerView.layoutManager == null) {
                recyclerView.layoutManager = object : GridLayoutManager(mContext, 3) {
                    override fun canScrollVertically() = false
                }
            }
            if (item.picture.isNullOrEmpty()) {
                recyclerView.gone()
                recyclerView.adapter = null
            } else {
                recyclerView.visible()
                val adapter = PictureAdapter()
                adapter.bindToRecyclerView(recyclerView)
                adapter.setNewData(item.picture)
            }
        }
        /**
         * 评论图片适配器
         */
        private inner class PictureAdapter : BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_seller_discuss_picture) {
            override fun convert(helper: BaseViewHolder, item:String?) {
                val imageView = helper.getView<AppCompatImageView>(R.id.iv_image)
                glideImage(imageView, item ?: "", R.color.colorBack)
            }
        }
    }
    class AdapterStore :
        BaseQuickAdapter<StoreExaminationInfoEntity.ServeInfo.Store, BaseViewHolder>(R.layout.item_physical_store) {
        override fun convert(
            helper: BaseViewHolder,
            item: StoreExaminationInfoEntity.ServeInfo.Store?
        ) {
            helper.setText(R.id.tv_physical_store_name, item?.name)
                .setText(R.id.tv_physical_address, "距您${item?.distance}km · ${item?.address}")
        }
    }

    class ImageAdapter :
        BaseQuickAdapter<StoreExaminationInfoEntity.ServeInfo.Path, BaseViewHolder>(R.layout.item_image_view) {
        override fun convert(
            helper: BaseViewHolder,
            item: StoreExaminationInfoEntity.ServeInfo.Path?
        ) {
            glideImage(
                helper.getView<ResizableImageView>(R.id.resizable_image_view),
                item?.path ?: ""
            )
        }

    }
}